package com.smalltao.core.base.controller;

import com.smalltao.core.utils.ToolsUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;

/**
 * @author smallTao.liu
 * @version V1.0
 * @description
 * @date 2018/11/14 15:40
 */
public abstract class BaseController {

    protected Logger logger = LoggerFactory.getLogger(this.getClass());

    @Value("${server.servlet.context-path}")
    protected String serverPath;

    @Autowired
    protected HttpServletRequest request;

    @Autowired
    protected HttpServletResponse response;

    @Autowired
    protected HttpSession session;

    /**
     * 获取cookie
     *
     * @param cookieName
     * @return
     */
    protected String getCookie(String cookieName) {
        return ToolsUtil.getCookie(request, cookieName);
    }

    /**
     * 设置 cookie
     *
     * @param cookieName
     * @param value
     */
    protected void setCookie(String cookieName, String value) {
        ToolsUtil.setCookie(response, cookieName, value);
    }

    /**
     * 设置 cookie
     *
     * @param cookieName
     * @param value
     * @param maxAge
     */
    protected void setCookie(String cookieName, String value, int maxAge) {
        ToolsUtil.setCookie(response, cookieName, value, maxAge);
    }

    /**
     * 判断是否为Ajax请求
     *
     * @return
     */
    public boolean isAjax() {
        return ToolsUtil.isAjax(request, response, serverPath);
    }

    /**
     * 获得工程根目录
     *
     * @return
     */
    protected String getRootPath() {
        return request.getServletContext().getRealPath("/");
    }

    /**
     * 获得工程根目录的上级目录 即tomcat部署路径tomcat/webapps/
     *
     * @return
     */
    protected String getRootPrePath() {
        return new File(getRootPath()).getParent() + "\\";
    }

    /**
     * 页面重定向
     *
     * @param url
     * @throws IOException
     */
    protected void toPage(String url) {
        try {
            response.sendRedirect(url);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
